package com.xique.park.controller.xj;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.xique.common.core.domain.R;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.bean.domain.ParkXjReduction;
import com.xique.park.bean.transform.xj.ParkXjReductionFrom;
import com.xique.park.bean.vo.xj.ParkXjReductionVo;
import com.xique.park.config.XiaojuConfig;
import com.xique.park.service.service.IParkXjReductionService;
import com.xique.park.utils.XjSignUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/park")
@Log4j2
public class ParkXjReductionController {

    @Autowired
    private IParkXjReductionService parkXjReductionService;

    @Autowired
    private XiaojuConfig xiaojuConfig;

    @PostMapping("/reduction")
    public AjaxResult reduction(@Validated @RequestBody ParkXjReductionVo parkXjReductionVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return AjaxResult.error(bindingResult.getFieldError().getDefaultMessage());
        }
        log.info("小桔传的参数 ：" + JSONArray.toJSON(parkXjReductionVo).toString());
        if (!XjSignUtils.verifyReq(parkXjReductionVo)) {
            log.info("小桔参数不合法 ：" + parkXjReductionVo.getSign());
            return AjaxResult.error(10010, "参数不合法", null);
        }
        System.out.println("********************" + xiaojuConfig.getSignKey());

        boolean bool = XjSignUtils.signVerification(parkXjReductionVo, xiaojuConfig.getSignKey(), parkXjReductionVo.getSign());
        if (!bool) {
            log.info("小桔签名错误 ：" + parkXjReductionVo.getSign());
            return AjaxResult.error(10007, "签名错误", null);
        }
        ParkXjReduction parkXjReduction = ParkXjReductionFrom.ParkXjReductionVo(parkXjReductionVo);
        return parkXjReductionService.getReduction(parkXjReduction, parkXjReductionVo.getMerchId());
    }

    @GetMapping("/plate/{plate}/{plateId}")
    public R getParkXjReduction(@PathVariable("plate") String plate, @PathVariable("plateId") Integer plateId) {
        log.info("查询减免接口：车牌 ：" + plate + "  park_id：" + plateId);
        ParkXjReduction parkXjReduction=parkXjReductionService.getPlate(plate, plateId);
        if (ObjectUtil.isEmpty(parkXjReduction)) {
            log.info("查询减免接口：车牌:{}, 车场id：{}, 结果：{}", plate, plateId, parkXjReduction);
            return R.fail();
        }
        log.info(JSONArray.toJSON(parkXjReduction).toString());
        return R.ok(parkXjReduction);
    }


    @PutMapping("/reliefstatus")
    public R updateStatus(@RequestBody ParkXjReduction parkXjReduction) {
        log.info("修改减免状态");
        return parkXjReductionService.updateStatus(parkXjReduction);
    }


}
